<template>
	<view>
		<u-form  :model="params" :rules="rules" ref="uForm" :errorType="errorType" >

			<view class="box2">
				<view class="profily">
					
					<view style="margin-top: -20px;">
						<u-form-item :rightIconStyle="{color: '#888', fontSize: '50rpx'}" prop="albumTitle" :label-position="labelPosition" label="相册标题" label-width="150" :required="true"> <!-- icon：right-icon="kefu-ermai" -->
							<u-input :border="border" placeholder="简短的相册标题" v-model="album.albumTitle" type="text"></u-input>
						</u-form-item>
						
						<u-form-item :rightIconStyle="{color: '#888', fontSize: '50rpx'}" prop='classificationName' :label-position="labelPosition" label="相册分类" label-width="150" :required="true">
							<u-input :border="border" placeholder="相册分类" v-model="album.classificationName" type="select"  @click="classificationListShow = true" />
							<u-action-sheet :list="classificationList" v-model="classificationListShow" @click="actionClassification"></u-action-sheet>
						</u-form-item>	
						
					</view>
				</view>
			</view>
			
			<view class="box3">
				<view class="profily">
					
					<view style="margin-top: -20px; display: block;">
						<view>
							<u-form-item :label-position="labelPosition" label="详细描述" prop="detailedDescription" label-width="150" :required="true"></u-form-item>
							<kn-edit ref="contentEdit" showInsertImg :pageScrollTop="pageScrollTop" v-model="album.albumDescription"></kn-edit>
						</view>
						<view>
							<u-form-item :label-position="labelPosition" label="图片上传" label-width="150" :required="true"></u-form-item>
							 <jade-image-upload
								 :list="media"
								 :control="control"
								 :columnType="columnType"
								 :maxCount="maxCount"
								 :compressSize="compressSize"
								 :compressQuality="compressQuality"
								 :compressWidth='compressWidth'
								 :imageSize="imageSize"
								 @chooseFile="chooseFile"
								 @imgDelete="mediaDelete"
							 >
							</jade-image-upload>
						</view>
					</view>
				</view>
			</view>
			
			<button class="button" @click="submit">提交</button>
		</u-form>
		<view style="height: 30px;"></view>
	</view>
</template>

<script>
	//富文本编辑器
	import knEdit from '@/components/lf-kn-editor/kn_editor.vue'
	//图片上传地址
	import url from '../../common/url.js';
	//图片上传
	import jadeImageUpload from '@/components/jade-image-upload/jade-image-upload.vue';
    export default {
		components: {
			knEdit,
			jadeImageUpload,
		},
        data() {
            return {
				classificationList:[],
				classificationListShow: false,
				album: {
					albumTitle: '',
					albumClassification: '',
					albumDescription: '',
					activityPictureId: '',
					userId: this.$store.state.vuex_user.openId
				},
				rules: {
					albumTitle: [
						{
							required: true, 
							message: '标题不能为空',
							trigger: 'change',
						}
					],
					classificationName: [
						{
							required: true, 
							message: '请选择类别',
							trigger: 'change',
						}
					],
					detailedDescription: [
						{
							required: true, 
							message: '请填写详细描述',
							trigger: 'change',
						}
					],
				},
				/* 上传图片 */
				control: true,
				columnType: 'other',
				maxCount: 6,
				compressSize: 0.2,
				imageSize: 2,
				compressQuality: 0.8,
				compressWidth: 375,
				uploadTask: null,
				media: [], //数据源
				edit: 0, /* 0为添加, 1为编辑*/
            }
        },
        onLoad(params) {
        	if(params.albumInfo != null) {
        		//确定添加or编辑、详情赋值、图片urlList赋值
        		this.edit = 1
        		this.album = JSON.parse(decodeURIComponent(params.albumInfo))
        		
        		this.album.imageUrlList.forEach((url, index) => {
        			const item = {
        				status: 'success',
        				progress: '上传成功',
        				src: url,
        			}
        			this.media.splice(index, 1, item)
        		})
        	}
           this.getClassificationList();
        },
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			// 设置表单校验规则 否则表单校验无效
			this.$refs.uForm.setRules(this.rules);
		},
        methods: {
			actionClassification(index) {
				this.album.albumClassification = this.classificationList[index].value
				this.album.classificationName = this.classificationList[index].label
			},
			//获取类别列表
			async getClassificationList() {
				const params = {
					index: 2
				}
				await this.$u.api.getClassificationList(params).then(res=>{
					if(res.code == 200) {
						this.classificationList = res.data
					} else {
						uni.showToast({
							icon:"error",
							title:"类别获取失败"
						})
					}
				})
			},
			submit() {
				//封装图片UrlList
				const imageUrlList = []
				this.media.forEach(res=>{
					imageUrlList.push(res.src)
				})
				this.album.imageUrlList = imageUrlList
				// console.log(this.imageUrlList);
				debugger
				this.$refs.uForm.validate(valid => {
					// console.log(this.album);
					if (valid) {
						if(this.edit == 0) {
							this.$u.api.albumAdd(this.album).then(res=> {
								if(res.code==200) {
									this.$u.route({
										type: 'reLaunch',
										url: 'pages/album/album',
									})
									uni.showToast({
										icon: 'success',
										title:"发布成功"
									})
								} else {
									uni.showToast({
										icon: 'error',
										title:"发布失败"
									})
								}
							})
						} else {
							this.$u.api.albumUpdate(this.album).then(res=> {
								if(res.code==200) {
									this.$u.route({
										type: 'reLaunch',
										url: '/pages/album/album?albumInfo=' + encodeURIComponent(JSON.stringify(this.album)),
									})
									uni.showToast({
										icon: 'success',
										title:"编辑成功"
									})
								} else {
									uni.showToast({
										icon: 'error',
										title:"编辑失败"
									})
								}
							})
						}
					} else {
						uni.showToast({
							icon: 'error',
							title:"请仔细填写内容哦"
						})
					}
				});
			},
			
			/* 上传图片 */
			
			//上传
			chooseFile(e) {
				this.uploadFileToServe(e)
			},
			//中断上传并删除
			mediaDelete(e) {
				// console.log("e = ", e);
				// console.log("this.media[e].src = ", this.media[e].src);
				//从七牛云删除
				this.$u.api.deleteImg(this.media[e].src)
				
				this.uploadTask ? this.uploadTask.abort() : ''
				this.media.splice(e,1)
			},
			//上传逻辑处理
			uploadFileToServe(urlList) {
				if (!urlList || urlList.length <= 0) {
					return
				};
				//以七牛云为例,可根据实际需求灵活调整
				urlList.forEach((item) => {
					this.uploadTask = uni.uploadFile({
						url: url.uploadUrl, //后端上传接口
						filePath: item.src,
						fileType:'image',
						name: 'image', //后台对应的参数名
						
						success: (res) => {
							let data = JSON.parse(res.data) //后端返回的数据
							if (data.code==200) {
								item.status = 'success'
								item.progress = '上传成功'
								item.src = data.data
							} else {
								item.status = 'error'
								item.progress = '上传失败'
							}
						}
					});
					this.uploadTask.onProgressUpdate((res) =>{
						item.percent = res.progress
						this.media.splice(item.index,1,item)
					})
				})
				// console.log("this.album.imageUrlList = ", this.album.imageUrlList);
				// console.log("this.media = ", this.media);
			},
        }
    }
</script>

<style lang="scss">
	.box2 {
		position: relative;
		padding-top: 13px;
		.profily {
			positio: absolute;
			width: 90%;
			height: 125px;
			border:1px solid #F7F7F7;
			border-radius: 10px;
			margin: 0 auto;
			top: -100upx;
			left: 5%;
			background: #FEFEFE;
			padding: 35upx;
			box-sizing: border-box;
			box-shadow: 2px 2px 5px #bebebe;
		}
	}	
	.box3 {
		position: relative;
		padding-top: 13px;
		display: flex;
		.profily {
			positio: absolute;
			width: 90%;
			// height: 500px;
			display: flex;
			border:1px solid #F7F7F7;
			border-radius: 10px;
			margin: 0 auto;
			top: -100upx;
			left: 5%;
			background: #FEFEFE;
			padding: 35upx;
			box-sizing: border-box;
			box-shadow: 2px 2px 5px #bebebe;
		}
	}
	.button {
		margin-top: 30px;
		background-color: #193867;
		color:white;
		width: 380px;
		height: 40px;
		border:0;
		font-size: 16px;
		color: #f2f2f2;
		border-radius: 30px;
	}
</style>